<template>
  <el-form
    ref="form1"
    size="small"
    :rules="rules"
    :model="form1"
    label-width="100px"
    inline
  >
    <div>
      <el-form-item
        label="名称"
        prop="name"
      ><el-input
        v-model="form1.name"
        type="text"
        placeholder="限30个字"
        maxlength="30"
        show-word-limit
        style="width:200px;"
      /></el-form-item>
    </div>
    <div>
      <el-form-item
        label="货号"
        prop="item_no"
      ><el-input
        v-model="form1.item_no"
        :disabled="isEdit"
        type="text"
      />如果您不输入商品货号，系统将自动生成一个唯一的货号
      </el-form-item>
    </div>
    <div>
      <el-form-item label="分类" prop="kind">
        <el-cascader
          v-model="form1.kind"
          :disabled="isEdit && spu !== 0"
          :options="kind"
          :props="casProps"
          clearable
          @change="hanldeChange"
        />
      </el-form-item>
    </div>
    <div>
      <el-form-item label="品牌" prop="brand">
        <el-select v-model="form1.brand" placeholder="请选择">
          <el-option
            v-for="item in brand"
            :key="item.id"
            :label="item.zh_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </div>
    <div>
      <el-form-item label="积分商品">
        <el-switch
          v-model="form1.is_points"
          active-color="#13ce66"
          :active-value="1"
          :inactive-value="0"
          @change="isPointsChange"
        />
      </el-form-item>
    </div>
    <div>
      <el-form-item
        v-if="form1.is_points === 0"
        label="成本价"
        prop="cost"
      ><el-input
        v-model="form1.cost"
        type="number"
        :disabled="isEdit && $route.name === 'VipGoods'"
        style="width:150px;"
      >
        <template slot="append">元</template>
      </el-input></el-form-item>
      <el-form-item
        v-if="form1.is_points === 0"
        label="原价"
        prop="original_price"
      ><el-input
        v-model="form1.original_price"
        type="number"
        :disabled="isEdit && $route.name === 'VipGoods'"
        style="width:150px;"
      >
        <template slot="append">元</template>
      </el-input></el-form-item>
      <el-form-item
        label="现价"
        prop="price"
      ><el-input
        v-model="form1.price"
        type="number"
        :disabled="isEdit && $route.name === 'VipGoods'"
        style="width:150px;"
      >
        <template slot="append">元</template>
      </el-input></el-form-item>
      <el-form-item
        v-if="form1.is_points === 1"
        label="积分"
        prop="points"
      ><el-input
        v-model="form1.points"
        type="number"
        :disabled="isEdit && $route.name === 'VipGoods'"
        :min="1"
        style="width:150px;"
      >
        <template slot="append">元</template>
      </el-input></el-form-item>
      <el-form-item
        v-if="form1.is_points === 0"
        label="vip价"
        prop="discount_price"
      ><el-input
        v-model="form1.discount_price"
        type="number"
        :disabled="vipDisable"
        style="width:150px;"
      >
        <template slot="append">元</template>
      </el-input></el-form-item>
    </div>
    <div>
      <el-form-item
        label="库存"
        prop="inventory"
      ><el-input v-model="form1.inventory" :disabled="isEdit" type="number" /></el-form-item>
      <el-form-item
        label="库存预警数"
        prop="inventory_caution"
      ><el-input v-model="form1.inventory_caution" type="number" /></el-form-item>
    </div>
    <div>
      <el-form-item
        style="white-space: nowrap"
        label="单人限购数量"
        prop="quota"
      ><el-input v-model="form1.quota" style="width:200px;" type="number" />
        值为0时，不限购</el-form-item>
    </div>
    <div>
      <el-form-item label="封面图">
        <el-upload
          action="https://wx.chengkenet.com/api/common/upload/"
          :headers="{
            Authorization: `Bearer ${getToken()}`
          }"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="coverRemove"
          :on-success="coverUpload"
          :file-list="form1.img_show"
          :limit="1"
        >
          <i class="el-icon-plus" />
          <div slot="tip" class="el-upload__tip">建议尺寸：750px*750px</div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
    </div>
    <div>
      <el-form-item label="轮播图" prop="commodity_img">
        <el-upload
          action="/#"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="imgRemove"
          :file-list="form1.commodity_img"
          multiple
          :http-request="imgUpload"
        >
          <i class="el-icon-plus" />
          <div slot="tip" class="el-upload__tip">建议尺寸：750px*750px</div>
        </el-upload>
      </el-form-item>
    </div>
    <div>
      <el-form-item label="封面视频">
        <el-upload
          action="https://wx.chengkenet.com/api/common/upload/"
          :headers="{
            Authorization: `Bearer ${getToken()}`
          }"
          :on-remove="videoRemove"
          :on-success="videoUpload"
          :file-list="form1.commodity_video"
          :limit="1"
        >
          <el-button size="small" type="primary">上传视频</el-button>
        </el-upload>
      </el-form-item>
    </div>
    <div>
      <el-form-item label="参数">
        <el-input
          v-model="form1.parameter"
          type="textarea"
          :rows="5"
          placeholder="输完一行参数请按回车换行，例如：型号：012345"
          resize="none"
          style="width:300px;"
        /></el-form-item>
    </div>
    <div>
      <el-form-item label="商品运费" prop="freight">
        <el-input v-model="form1.freight" style="width:150px;" type="number" />
        值为0时为包邮</el-form-item>
    </div>
    <div>
      <el-form-item label="是否为服务">
        <el-switch
          v-model="form1.is_serve"
          :disabled="isEdit"
          active-color="#13ce66"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
      <el-form-item label="新品">
        <el-switch
          v-model="form1.is_new"
          active-color="#13ce66"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
      <el-form-item label="推荐">
        <el-switch
          v-model="form1.is_recommend"
          active-color="#13ce66"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
      <el-form-item label="是否商城展示">
        <el-switch
          v-model="form1.is_shop_show"
          active-color="#13ce66"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </div>
  </el-form>
</template>

<script>
import { getToken } from '@/utils/auth'
import { fileUpload } from '@/api/file'
import { mapGetters } from 'vuex'
import {
  editGoodGetParamsOne,
  editGoodOne,
  getGoodDetailOne,
  editGoodDetailOne
} from '@/api/good-mng'
const validateAcquaintance = (rule, value, callback) => {
  if (value >= 10 || value < 0) {
    callback(new Error('折扣应在 0 至 9.99 之间'))
  } else {
    callback()
  }
}
const pointsValidate = (rule, value, callback) => {
  if (value < 1) {
    callback(new Error('积分至少为1点'))
  } else {
    callback()
  }
}
export default {
  props: ['goodDetail', 'step', 'isEdit'],
  data() {
    return {
      commodityFirstCateId: '',
      form1: {
        name: '',
        kind: null,
        brand: null,
        cost: null,
        original_price: 0,
        points: 0,
        price: null,
        discount_price: null,
        inventory_caution: null,
        inventory: null,
        quota: 0,
        img_show: [],
        commodity_img: [],
        commodity_video: [],
        freight: 0,
        parameter: null,
        is_new: 0,
        is_recommend: 0,
        item_no: null,
        is_shop_show: 0,
        is_serve: 0,
        is_points: 0
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        kind: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        brand: [{ required: true, message: '请选择品牌', trigger: 'blur' }],
        cost: [{ required: true, message: '请输入成本价', trigger: 'blur' }],
        price: [{ required: true, message: '请输入折扣价', trigger: 'blur' }],
        original_price: [
          { required: true, message: '请输入原价', trigger: 'blur' }
        ],
        // discount_price: [
        //   { required: true, message: '请输入会员价', trigger: 'blur' }
        // ],
        inventory_caution: [
          { required: true, message: '请输入库存预警数', trigger: 'blur' }
        ],
        inventory: [{ required: true, message: '请输入库存', trigger: 'blur' }],
        commodity_img: [
          { required: true, message: '请上传商品轮播图', trigger: 'blur' }
        ],
        freight: [{ required: true, message: '请输入运费', trigger: 'blur' }],
        freight_intro: [
          { required: true, message: '请输入运费', trigger: 'blur' }
        ],
        quota: [{ required: true, message: '请输入限购数量', trigger: 'blur' }],
        points: [{ validator: pointsValidate, trigger: 'blur' }]
      },
      brand: [],
      kind: [],
      casProps: {
        expandTrigger: 'hover',
        // checkStrictly: true,
        value: 'id',
        label: 'kind_name',
        children: 'lower'
      },
      dialogVisible: false,
      dialogImageUrl: '',
      spu: 0
    }
  },
  computed: {
    ...mapGetters(['vip_rule']),
    vipDisable() {
      const disable = JSON.parse(localStorage.getItem('vip_rule')) === 0
      return disable
    }
  },
  watch: {
    goodDetail: function(val) {
      this.commodityFirstCateId = val.commodity_first_cate_id
      this.form1.name = val.name
      this.form1.brand = val.brand_id
      this.form1.kind = [val.higherup, val.commodity_kind_id]
      this.form1.cost = val.cost
      this.form1.discount_price = val.discount_price
      this.form1.freight = val.freight
      this.form1.inventory = val.inventory
      this.form1.inventory_caution = val.inventory_caution
      this.form1.is_new = val.is_new
      this.form1.is_recommend = val.is_recommend
      this.form1.is_shop_show = val.is_shop_show
      this.form1.quota = val.quota
      this.form1.name = val.name
      this.form1.original_price = val.original_price
      this.form1.price = val.price
      this.form1.item_no = val.item_no
      this.form1.is_serve = val.is_serve
      this.form1.is_points = val.is_points
      this.form1.points = -(-val.points)
      this.form1.commodity_first_cate_id = val.commodity_first_cate_id
      if (val.img_show) { this.form1.img_show.push({ name: '', url: val.img_show }) }
      // this.form1.ratio = val.ratio;
      // this.form1.vip_ratio = val.vip_ratio;
      // this.form1.freight_intro = val.freight_intro;
      this.spu = val.spu
      let str = ''
      if (val.parameter && val.parameter.length) {
        val.parameter.forEach((item, index) => {
          str +=
            item.name +
            ':' +
            item.detail +
            (index !== val.parameter.length - 1 ? '\n' : '')
        })
        this.form1.parameter = str
      }
      if (val.commodity_video) {
        this.form1.commodity_video.push({
          name: val.commodity_video,
          url: val.commodity_video
        })
      }
      val.commodity_img.forEach(item => {
        this.form1.commodity_img.push({ name: '', url: item })
      })
    },
    step: function(val) {
      if (val !== 0) {
        this.$refs['form1'].resetFields()
      }
    }
  },
  created() {
    editGoodGetParamsOne().then(res => {
      if (res.code === 200) {
        this.brand = res.data.brand
        this.kind = res.data.kind
      }
    })
  },
  methods: {
    isPointsChange(val) {
      if (val === 0) {
        this.form1.points = 0
      } else {
        this.form1.points = 1
      }
    },
    hanldeChange(val) {
      this.commodityFirstCateId = val[0]
    },
    submit() {
      this.$refs['form1'].validate(valid => {
        if (valid) {
          const data = {
            id: this.goodDetail.id ? this.goodDetail.id : undefined,
            name: this.form1.name,
            kind: this.form1.kind[1],
            commodity_first_cate_id: this.commodityFirstCateId,
            brand: this.form1.brand,
            cost: this.form1.is_points === 0 ? this.form1.cost : 0,
            item_no: this.form1.item_no,
            original_price:
              this.form1.is_points === 0 ? this.form1.original_price : 0,
            discount_price:
              this.form1.is_points === 0 ? this.form1.discount_price : 0,
            price: this.form1.price,
            inventory: this.form1.inventory,
            inventory_caution: this.form1.inventory_caution,
            img_show: this.form1.img_show[0]
              ? this.form1.img_show[0].url
              : null,
            freight: this.form1.freight ? this.form1.freight : 0,
            quota: this.form1.quota,
            commodity_video: this.form1.commodity_video[0]
              ? this.form1.commodity_video[0].url
              : null,
            is_new: this.form1.is_new,
            is_recommend: this.form1.is_recommend,
            is_shop_show: this.form1.is_shop_show,
            // ratio: this.form1.ratio,
            // vip_ratio: this.form1.vip_ratio,
            is_vip: this.$route.name === 'VipGoods' ? 1 : 0,
            is_serve: this.form1.is_serve,
            is_points: this.form1.is_points,
            points: this.form1.points
          }
          data.commodity_img = this.form1.commodity_img.map(item => {
            return item.url
          })
          if (this.form1.parameter) {
            const arr = this.form1.parameter.split('\n')
            let paramValid = true
            const result = arr.map(item => {
              let param = item.split(':')
              if (param.length === 1) param = item.split('：')
              if (param.length === 1) paramValid = false
              return {
                name: param[0],
                detail: param[1]
              }
            })
            if (!paramValid) {
              this.$message.error('参数格式不正确')
              return
            }
            data.parameter = result
          } else {
            data.parameter = ''
          }

          if (this.isEdit) {
            if (this.spu) {
              editGoodDetailOne(data).then(res => {
                if (res.code === 200) {
                  this.$emit('editNextStep')
                }
              })
              console.log(111)
            } else {
              editGoodDetailOne(data).then(res => {
                if (res.code === 200) {
                  this.$emit('changeEdit', false)
                  this.$emit('nextStep', this.goodDetail.id)
                }
              })
              console.log(222)
            }
          } else {
            editGoodOne(data).then(res => {
              if (res.code === 200) {
                this.$emit('nextStep', res.data.id, this.commodityFirstCateId)
              }
            })
            console.log(333)
          }
        } else {
          // console.log('error submit!!');
          return false
        }
      })
    },
    videoUpload(response, file, fileList) {
      this.form1.commodity_video.push({
        name: response.data.file,
        url: response.data.file,
        uid: file.uid
      })
    },
    videoRemove(file, fileList) {
      console.log(file)
      this.form1.commodity_video.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form1.commodity_video.splice(index, 1)
          return
        }
      })
    },
    coverUpload(response, file, fileList) {
      this.form1.img_show.push({ name: '', url: response.data.file })
    },
    coverRemove(file, fileList) {
      this.form1.img_show.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form1.img_show.splice(index, 1)
          return
        }
      })
    },
    imgUpload(file) {
      console.log(file)
      const formData = new FormData()
      formData.append('file', file.file)
      fileUpload(formData).then(res => {
        if (res.code === 200) {
          this.form1.commodity_img.push({
            name: '',
            url: res.data.file,
            uid: file.file.uid
          })
        }
      })
    },
    imgRemove(file, fileList) {
      this.form1.commodity_img.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form1.commodity_img.splice(index, 1)
          return
        }
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    getToken() {
      return getToken()
    },
    goodInfoSubmit() {}
  }
}
</script>

<style lang="scss"></style>
